<template>
  <div class="office-pdf-container">
    <div class="main-content">
      <div class="content-header">
        <h1 class="page-title">Office文档转PDF</h1>
        <p class="page-subtitle">将Word、Excel、PPT等Office文档快速转换为PDF格式</p>
      </div>

      <div class="conversion-section">
        <div class="upload-area">
          <div class="upload-container">
            <div class="upload-icon">📄</div>
            <h3>选择要转换的文件</h3>
            <p>支持 .doc, .docx, .xls, .xlsx, .ppt, .pptx 等格式</p>

            <div class="file-input-container">
              <input
                type="file"
                ref="fileInput"
                @change="handleFileSelect"
                multiple
                accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
                id="file-upload"
                style="display: none"
              />
              <button
                class="upload-btn"
                @click="$refs.fileInput.click()"
                :disabled="isConverting"
              >
                <span v-if="!isConverting">📁 选择文件</span>
                <span v-else class="loading">⏳ 处理中...</span>
              </button>
            </div>
          </div>

          <div class="format-options">
            <h4>转换选项</h4>
            <div class="options-grid">
              <label class="option-item">
                <input
                  type="radio"
                  v-model="outputFormat"
                  value="pdf"
                  checked
                />
                <div class="option-content">
                  <div class="option-icon">📄</div>
                  <span>PDF 格式</span>
                </div>
              </label>

              <label class="option-item">
                <input
                  type="radio"
                  v-model="outputFormat"
                  value="merge"
                />
                <div class="option-content">
                  <div class="option-icon">🔗</div>
                  <span>合并PDF</span>
                </div>
              </label>

              <label class="option-item">
                <input
                  type="checkbox"
                  v-model="keepOriginal"
                />
                <div class="option-content">
                  <div class="option-icon">💾</div>
                  <span>保留原文件</span>
                </div>
              </label>
            </div>
          </div>
        </div>

        <div class="files-section">
          <div class="files-header">
            <h3>待处理文件</h3>
            <div class="files-count">
              {{ selectedFiles.length }} 个文件
              <span v-if="totalSize">({{ formatFileSize(totalSize) }})</span>
            </div>
          </div>

          <div class="files-list">
            <div
              v-for="file in selectedFiles"
              :key="file.id"
              class="file-item"
              :class="{ converting: file.isConverting, converted: file.isConverted }"
            >
              <div class="file-info">
                <div class="file-icon">{{ getFileIcon(file) }}</div>
                <div class="file-details">
                  <div class="filename">{{ file.name }}</div>
                  <div class="file-meta">
                    <span class="size">{{ formatFileSize(file.size) }}</span>
                    <span class="status">{{ getFileStatus(file) }}</span>
                  </div>
                </div>
              </div>

              <div class="file-actions">
                <button
                  v-if="!file.isConverting && !file.isConverted"
                  class="convert-btn"
                  @click="convertFile(file)"
                >
                  ✨ 转换
                </button>
                <button
                  v-if="file.isConverted"
                  class="download-btn"
                  @click="downloadFile(file)"
                >
                  📥 下载
                </button>
                <button
                  class="remove-btn"
                  @click="removeFile(file)"
                >
                  🗑️
                </button>
              </div>
            </div>

            <div v-if="selectedFiles.length === 0" class="empty-state">
              <div class="empty-icon">📂</div>
              <p>暂无文件，请先选择文件</p>
            </div>
          </div>

          <div class="batch-actions" v-if="selectedFiles.length > 0">
            <button
              class="batch-convert-btn"
              @click="convertAllFiles"
              :disabled="isConverting || hasConvertingFiles"
            >
              <span v-if="!isConverting">🚀 批量转换</span>
              <span v-else class="loading">⏳ 批量处理中...</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 状态管理
const selectedFiles = ref([])
const isConverting = ref(false)
const outputFormat = ref('pdf')
const keepOriginal = ref(false)

// 文件ID生成器
let fileIdCounter = 0
function generateFileId() {
  return ++fileIdCounter
}

// 计算属性
const totalSize = computed(() => {
  return selectedFiles.value.reduce((total, file) => total + file.size, 0)
})

const hasConvertingFiles = computed(() => {
  return selectedFiles.value.some(file => file.isConverting)
})

// 模块初始化
onMounted(() => {
  console.log('Office PDF module loaded')
})

/**
 * 处理文件选择
 */
function handleFileSelect(event) {
  const files = Array.from(event.target.files)
  files.forEach(file => {
    selectedFiles.value.push({
      id: generateFileId(),
      name: file.name,
      size: file.size,
      type: file.type,
      file: file,
      isConverting: false,
      isConverted: false,
      convertedData: null,
      progress: 0
    })
  })
}

/**
 * 转换单个文件
 */
async function convertFile(file) {
  file.isConverting = true
  file.progress = 0

  try {
    // 模拟转换过程
    for (let i = 0; i <= 100; i += 10) {
      file.progress = i
      await new Promise(resolve => setTimeout(resolve, 50))
    }

    // 模拟生成PDF数据
    file.convertedData = new Blob(['PDF content'], { type: 'application/pdf' })
    file.isConverted = true
  } catch (error) {
    console.error('Conversion failed:', error)
    alert('文件转换失败，请重试')
  } finally {
    file.isConverting = false
  }
}

/**
 * 批量转换
 */
async function convertAllFiles() {
  isConverting.value = true
  const filesToConvert = selectedFiles.value.filter(file => !file.isConverted && !file.isConverting)

  for (const file of filesToConvert) {
    await convertFile(file)
  }

  isConverting.value = false
}

/**
 * 下载文件
 */
function downloadFile(file) {
  if (!file.convertedData) return

  const url = URL.createObjectURL(file.convertedData)
  const a = document.createElement('a')
  a.href = url
  a.download = file.name.replace(/\.[^/.]+$/, '.pdf')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

/**
 * 移除文件
 */
function removeFile(file) {
  const index = selectedFiles.value.indexOf(file)
  if (index > -1) {
    selectedFiles.value.splice(index, 1)
  }
}

/**
 * 获取文件图标
 */
function getFileIcon(file) {
  const ext = file.name.split('.').pop()?.toLowerCase()
  const icons = {
    doc: '📝',
    docx: '📝',
    xls: '📊',
    xlsx: '📊',
    ppt: '📽️',
    pptx: '📽️',
    pdf: '📄'
  }
  return icons[ext] || '📄'
}

/**
 * 获取文件状态
 */
function getFileStatus(file) {
  if (file.isConverted) return '✅ 已转换'
  if (file.isConverting) return '⏳ 转换中...'
  return '⏳ 待转换'
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>